package scparser.factory.sceneFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import model.Scene;

import scparser.ParserHelper;
import scparser.factory.primitiveFactory.FactoryException;
import scparser.factory.primitiveFactory.GenericMeshFactory;
import scparser.factory.primitiveFactory.PlaneFactory;
import scparser.factory.primitiveFactory.PrimitiveAbstractFactory;
import scparser.factory.primitiveFactory.SphereFactory;

public class SceneObjectFactory extends SceneFactory {
	
	
	public SceneObjectFactory(Scene scene) {
		super.scene = scene;
	}

	@Override
	public Object create(BufferedReader br) throws FactoryException {
		List<String> block = new ArrayList<String>();
		String line = null;
		String type = null;
		PrimitiveAbstractFactory pf = null;
		int brackets = 1;
		
		try {
			while ((line = br.readLine()) != null) {
				line = line.trim();
				if (line.startsWith("type")) {
					type = ParserHelper.takeString(line, "type");
				} else if (line.contains("{")) {
					if (!line.contains("}")) {
						brackets++;
					}
				} else if (line.contains("}")) {
					if (brackets == 1) {
						break;
					}
					
					if (brackets == 0) {
						throw new FactoryException("syntax error, check your brackets");
					}

					brackets--;
				}
				block.add(line);
			}
		} catch (IOException e) {
			throw new FactoryException(e.getMessage());
		}
		

		if (type == null) {
			throw new FactoryException("type missing");
		}
		
		if (type.equals("generic-mesh")) {
			pf = new GenericMeshFactory(scene);
		}
		
		if (type.equals("sphere")) {
			pf = new SphereFactory(scene);
		}
		
		if (type.equals("plane")) {
			pf = new PlaneFactory(scene);
		}
		
		if (type.equals("box")) {
			//TODO future implementation
		}
		
		
		return pf.create(block);
	}

}
